package com.wangzh.concurrent.lock;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;

//锁升级过程
public class Test1 {

    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();

        System.out.println(ClassLayout.parseInstance(o).toPrintable());

//        synchronized (o){
//            System.out.println(ClassLayout.parseInstance(o).toPrintable());
//        }

//      jvm参数有默认值 超过3秒，开启偏量锁     MarkWord 00000101
//        TimeUnit.SECONDS.sleep(2);
//        Object o2 = new Object();
//        System.out.println(ClassLayout.parseInstance(o2).toPrintable());

        MyData myData = new MyData();
        Thread a = new Thread(() -> {
            for (int i = 0; i < 10; i++) {

                myData.setNumber(2);
            }
        }, "a");
        Thread b = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myData.getNumber();

            }
        }, "b");
        Thread c = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myData.getNumber();

            }
        }, "c");

        TimeUnit.SECONDS.sleep(1);
        System.out.println("准备开始---");
        a.start();
        b.start();
        c.start();
    }
}

class MyData{
    private int number;

    public synchronized int getNumber() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("get:"+Thread.currentThread().getName());

        return number;
    }

    public synchronized void setNumber(int number) {
        System.out.println("set:"+Thread.currentThread().getName());
        this.number = number;
    }
}
